package top.ezzz.controller;

import org.noear.solon.annotation.Controller;
import org.noear.solon.annotation.Mapping;
import org.noear.solon.annotation.Param;
import org.noear.solon.web.cors.annotation.CrossOrigin;
import org.noear.solon.core.handle.Context;
import org.noear.solon.core.handle.MethodType;
import top.ezzz.model.ProcessInfo;
import top.ezzz.model.SystemInfo;
import top.ezzz.tool.ProcessTask;
import top.ezzz.tool.R;
import top.ezzz.util.ProcessUtil;
import top.ezzz.util.SystemInfoUtil;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

@CrossOrigin
@Controller
public class ProcessController {

    @Mapping("/")
    public R run() {
        return R.success("Hello World!");
    }

    @Mapping("/system")
    public R system() {
        SystemInfo result = SystemInfoUtil.getSystemInfo();
        return R.success(result);
    }

    /**
     * 获取所有进程（优先从缓存获取）
     */
    @Mapping("/processes")
    public R getAllProcesses() {
        try {
            // 优先从缓存获取
            List<ProcessInfo> processes = ProcessTask.getCachedProcesses("all");
            if (processes == null) {
                // 缓存未命中，实时获取
                processes = ProcessUtil.getAllProcesses();
            }
            return R.success(processes);
        } catch (Exception e) {
            return R.fail("获取进程信息失败: " + e.getMessage());
        }
    }

    /**
     * 根据类型获取进程（优先从缓存获取）
     */
    @Mapping("/processes/{type}")
    public R getProcessesByType(@Param("type") String type) {
        try {
            // 优先从缓存获取
            List<ProcessInfo> processes = ProcessTask.getCachedProcesses(type);
            if (processes == null) {
                // 缓存未命中，实时获取
                processes = ProcessUtil.getProcessesByType(type);
            }
            return R.success(processes);
        } catch (Exception e) {
            return R.fail("获取" + type + "进程信息失败: " + e.getMessage());
        }
    }

    /**
     * 获取可用的进程类型
     */
    @Mapping("/process-types")
    public R getProcessTypes() {
        try {
            List<String> types = ProcessUtil.getAvailableProcessTypes();
            return R.success(types);
        } catch (Exception e) {
            return R.fail("获取进程类型失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取缓存状态
     */
    @Mapping("/process-cache-status")
    public R getCacheStatus() {
        try {
            List<String> cachedTypes = ProcessTask.getCachedTypes();
            return R.success(cachedTypes);
        } catch (Exception e) {
            return R.fail("获取缓存状态失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取日志文件列表
     */
    @Mapping("/logs/files")
    public R getLogFiles() {
        try {
            File logsDir = new File("logs");
            if (!logsDir.exists() || !logsDir.isDirectory()) {
                return R.fail("日志目录不存在");
            }
            
            List<String> logFiles = new ArrayList<>();
            File[] files = logsDir.listFiles((dir, name) -> name.endsWith(".log"));
            if (files != null) {
                for (File file : files) {
                    logFiles.add(file.getName());
                }
            }
            
            return R.success(logFiles);
        } catch (Exception e) {
            return R.fail("获取日志文件列表失败: " + e.getMessage());
        }
    }
    
    /**
     * 读取指定日志文件的内容
     */
    @Mapping("/logs/content")
    public R getLogContent(@Param("filename") String filename, 
                          @Param("lines") Integer lines) {
        try {
            // 安全检查，防止路径遍历攻击
            if (filename.contains("..") || filename.contains("/") || filename.contains("\\")) {
                return R.fail("无效的文件名");
            }
            
            Path logPath = Paths.get("logs", filename);
            if (!Files.exists(logPath)) {
                return R.fail("日志文件不存在");
            }
            
            // 默认读取最后1000行，如果指定了lines参数则使用指定值
            int lineCount = lines != null ? lines : 1000;
            
            // 使用UTF-8编码读取文件
            List<String> content = Files.lines(logPath, StandardCharsets.UTF_8)
                    .collect(Collectors.toList());
            
            // 如果文件行数超过指定行数，只返回最后N行
            if (content.size() > lineCount) {
                content = content.subList(content.size() - lineCount, content.size());
            }
            
            return R.success(content);
        } catch (Exception e) {
            return R.fail("读取日志文件失败: " + e.getMessage());
        }
    }
    
}
